<template>
	<div class="container">
		<el-row :gutter="20" class="main-row">
			<el-col :span="16" class="main-col">
				<el-row :gutter="20">
					<el-col :span="24" class="mb">
						<la-filter
							:classify="infor.classify"
							@toggleClassify="toggleClassify"
							@isShowImgTopic="isShowImgTopic"
							@search="search"
							@export="exportExam"
							@exportZip="exportZip"
						></la-filter>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="showImageContainer ? 12 : 24">
						<la-topic
							:topic="infor.topic"
							@prev="prevTopic"
							@next="nextTopic"
							@jump="jumpTopic"
						></la-topic>
					</el-col>
					<el-col :span="12" v-if="showImageContainer">
						<la-picture
							:topic="infor.topic"
							:isOpenSwitch="infor.curClassify && infor.curClassify.list && infor.curClassify.list[infor.topicIndex].confirmation"
							:isLoading="isPicSwitchLoading"
							:uploadAction="uploadUrl"
							@replacePic="replacePic"
							@switchChange="picSwitchChange"
							@uploadSuccess="uploadSuccess"
							@uploadError="uploadError"
						></la-picture>
					</el-col>
					<el-col :span="24" class="mt" v-if="showImageContainer">
						<la-picture-list :topic="infor.topic" @replacePic="replacePic"></la-picture-list>
					</el-col>
					<el-col :span="24" class="mt">
						<la-analysis :topic="infor.topic"></la-analysis>
					</el-col>
					<el-col :span="24" class="mt">
					</el-col>
				</el-row>
			</el-col>
			<el-col :span="8" class="main-col">
				<la-list
					:curIndex="infor.topicIndex"
					:list="infor.curClassify"
					@curItem="curTopic"
					@topicFilter="topicFilter"
				></la-list>
			</el-col>
		</el-row>

	</div>
</template>

<script>
import laFilter from './filter'
import laTopic from './topic'
import laList from './list'
import laAnalysis from './analysis'
import laPicture from './picture'
import laPictureList from './picture_list'
import { defineComponent, onMounted, reactive, inject, computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElLoading } from 'element-plus'
export default defineComponent({
	name: 'laMain',
	components: { laFilter, laTopic, laList, laAnalysis, laPicture, laPictureList },
	setup () {
		const route = useRoute()
		const store = useStore()
		const http = inject('http')
		const config = inject(route.name)
		const infor = reactive({})
		const isPicSwitchLoading = ref(false)
		let loading = null

		const load = () => {
			loading = ElLoading.service({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			http.get('getAllCrawler', {
				params: {
					pid: route.name
				}
			}).then(res => {
				if (res.status === 'ok') {
					infor.classify = res.message
					if (res.message.length > 0) {
						infor.curClassify = res.message[0]
						infor.curClassifyIndex = 0
						infor.topicIndex = 0
						loadTopicIds()
					}
				}
			}).catch(() => { loading.close() })
		}
		const loadTopicIds = () => {
			http.get('getQuesIds', {
				params: {
					pid: route.name,
					sid: infor.curClassify.searchId
				}
			}).then(res => {
				if (res.status === 'ok') {
					infor.curClassify.list = res.message
					loadTopic()
				}
			})
		}
		const loadTopic = () => {
			if (!infor.curClassify.list || infor.curClassify.list.length === 0) {
				ElMessage.error('题库内无题，题号清空，当前题不刷新')
				return
			}
			http.get('fetch', {
				params: {
					pid: route.name,
					_id: infor.curClassify.list[infor.topicIndex]._id
				}
			}).then(res => {
				if (res.status === 'ok') {
					infor.topic = loadTopicCallback(JSON.parse(JSON.stringify(config.data)), res.message)
				}
				loading.close()
			}).catch(() => { loading.close() })
		}
		const loadTopicCallback = (topic, data) => {
			Object.keys(topic).forEach(item => {
				if (typeof topic[item].key === 'string') {
					if (data[topic[item].key] || data[topic[item].key] === 0) topic[item].content = data[topic[item].key]
				} else {
					topic[item].key.forEach((val, index) => {
						if (data[val.key]) topic[item].key[index].content = data[val.key]
					})
				}
			})
			return topic
		}

		const toggleClassify = index => {
			infor.curClassify = infor.classify[index]
			infor.curClassifyIndex = index
			infor.topicIndex = 0
			loadTopicIds()
		}
		const jumpTopic = (index) => {
			if (!index) { ElMessage.error('请输入题号, 题号不能为空') }
			infor.topicIndex = index - 1
			loadTopic()
		}
		const prevTopic = () => {
			if (infor.topicIndex > 0) {
				infor.topicIndex--
				loadTopic()
			}
		}
		const nextTopic = () => {
			if (infor.topicIndex < infor.curClassify.list.length - 1) {
				infor.topicIndex++
				loadTopic()
			}
		}
		const curTopic = index => {
			if (infor.topicIndex !== index) {
				infor.topicIndex = index
				loadTopic()
			}
		}

		const replacePic = url => {
			http.post(`/api/uni/changeImage?pid=${route.name}`, {
				_id: infor.topic._id.content,
				url
			}).then(res => {
				if (res.status === 'ok') {
					ElMessage.success({
						message: '恭喜你，修改成功',
						type: 'success'
					})
					// Todo: 仅在替换为非原图时更改
					infor.curClassify.list[infor.topicIndex].isUserChange = true
					loadTopic()
				}
			})
		}
		const isShowImgTopic = (bool) => {
			if (bool === 'picture') {
				http.post(`/api/uni/filterMediaIds?pid=${route.name}`, {
					_ids: infor.curClassify.list.join(',')
				}).then(res => {
					if (res.status === 'ok') {
						infor.curClassify.list = res.message
						infor.topicIndex = 0
						loadTopic()
					}
				})
			} else {
				infor.curClassify = infor.classify[infor.curClassifyIndex]
				infor.topicIndex = 0
				loadTopic()
			}
		}

		const exportExam = () => {
			const path = process.env.NODE_ENV === 'production' ? window.location.origin : 'http://192.168.1.123:3000'
			const filename = route.meta.title + '--' + infor.curClassify.label
			window.open(`${path}/api/uni/export?pid=${route.name}&label=${infor.curClassify.label}&filename=${filename}`)
		}

		const exportZip = () => {
			const path = process.env.NODE_ENV === 'production' ? window.location.origin : 'http://192.168.1.123:3000'
			const filename = route.meta.title + '--' + infor.curClassify.label
			window.open(`${path}/api/uni/exportZip?pid=${route.name}&label=${infor.curClassify.label}&filename=${filename}`)
		}
		const search = (val) => {
			console.log(val)
		}
		const topicFilter = (val) => {
			const lsTopic = JSON.parse(JSON.stringify(infor.classify[infor.curClassifyIndex]))
			const listarr = ['pt', 'tp', 'sp']
			infor.curClassify = lsTopic
			if (val !== 'all') {
				const list = lsTopic.list.filter(item => {
					const index = listarr.indexOf(val)
					return item.mediaType === index
				})
				infor.curClassify.list = list
			}
			infor.topicIndex = 0
			loadTopic()
		}
		const picSwitchChange = () => {
			// console.log('change!')
			// console.log(isPicSwitchLoading)
			isPicSwitchLoading.value = true
			const cur = infor.curClassify.list[infor.topicIndex].confirmation
			http.get(cur ? 'undoConfirm' : 'confirm', {
				params: {
					pid: route.name,
					_id: infor.curClassify.list[infor.topicIndex]._id
				}
			}).then(res => {
				if (res.status === 'ok') {
					infor.curClassify.list[infor.topicIndex].confirmation = !cur
				}
				isPicSwitchLoading.value = false
			}).catch(() => { isPicSwitchLoading.value = false })
		}
		const uploadSuccess = () => {
			// console.log('上传成功！')
			ElMessage.success({
				message: '上传成功！',
				type: 'success'
			})
			infor.curClassify.list[infor.topicIndex].isUserChange = true
			loadTopic()
		}
		const uploadError = () => {
			ElMessage.error('上传失败！')
		}

		onMounted(() => { load() })
		return {
			infor,
			isPicSwitchLoading,
			jumpTopic,
			prevTopic,
			nextTopic,
			curTopic,
			replacePic,
			toggleClassify,
			isShowImgTopic,
			exportExam,
			exportZip,
			search,
			topicFilter,
			picSwitchChange,
			uploadUrl: computed(() => `/api/uni/uploadImage?pid=${route.name}&_id=${infor.topic._id.content}`),
			uploadSuccess,
			uploadError,
			loadState: computed(() => store.state.loadState),
			showImageContainer: computed(() =>
				infor.curClassify &&
				infor.curClassify.list &&
				infor.curClassify.list.length &&
				infor.curClassify.list[infor.topicIndex].mediaType === 1
			)
		}
	}
})
</script>

<style lang="scss" scoped>
.container {
	height: 100%;
	.main-row {
		height: 100%;
		.main-col {
			max-height: 100%;
			overflow-y: auto;
		}
	}
}
</style>
